package com.scut.fy.auth.service.impl;

import com.baomidou.mybatisplus.core.toolkit.BeanUtils;
import com.scut.fy.auth.feign.SysRoleService;
import com.scut.fy.auth.feign.SysUserService;
import com.scut.fy.auth.model.dto.SysRoleDto;
import com.scut.fy.auth.model.dto.SysUserDto;
import com.scut.fy.auth.model.dto.UserDetailsDto;
import com.scut.fy.common.web.util.HttpResult;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * TODO
 *
 * @author JY
 * @version 1.0
 * @date 2021/8/29
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private SysUserService sysUserService;

    @Resource
    private SysRoleService sysRoleService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        HttpResult<Map<String, Object>> ru = sysUserService.findUserByUserName(username);
        HttpResult<List<Map<String, Object>>> rr = sysRoleService.findRolesByUserName(username);

        if (ru.getData().size() > 0 && rr.getData().size() > 0) {
            // Map转换为object
            SysUserDto sysUserDto = BeanUtils.mapToBean(ru.getData(), SysUserDto.class);
            List<SysRoleDto> sysRoleDtoList = BeanUtils.mapsToBeans(rr.getData(), SysRoleDto.class);
            return new UserDetailsDto(sysUserDto, sysRoleDtoList);
        } else {
            return null;
        }
    }
}
